'''
Created on Jan 26, 2012

@author: TeFa
'''
from xml.etree import ElementTree
from podnapisi_sub_info import SubInfo
from cStringIO import StringIO
import zipfile
import hashlib
import xmlrpclib
import constants
import urllib
import httplib

class Api:
    sessionID = ""
    encodedParam = ""
    apiConnection = None
    currentSearchKeyword = ""
    currentSearchPage = 0
    totalSearchPageNumber = 0
    currentSubsDict = {}
    
    def __init__(self,userID):
        '''================================================================================================
        ===                                        __init__                                             ===
        ================================================================================================'''
        self.userID = userID
    
    def login(self,username,password):
        '''================================================================================================
        ===                                         login                                               ===
        ================================================================================================'''
        self.apiConnection = xmlrpclib.ServerProxy(constants.PODNAPISI_API_URI)
        initiateResponse = getattr(self.apiConnection, "initiate")(self.userID)
        self.sessionID = initiateResponse['session']
        randomNonce = initiateResponse['nonce']
        md5Hash = hashlib.md5(password).hexdigest()
        md5NonceHash = md5Hash + randomNonce
        passwordHash = hashlib.sha256(md5NonceHash).hexdigest()
        authenticationResponse = self.apiConnection.authenticate(self.sessionID,username,passwordHash)
        return authenticationResponse['status']
    
    def initSubsFromServer(self,keyword,page=1):
        '''================================================================================================
        ===                     private, initializes the current Subs Dictionary                        ===
        ================================================================================================'''
        params = urllib.urlencode({'sK': keyword,'sXML': '1', 'page': page})
        httpCon = httplib.HTTPConnection(constants.PODNAPISI_SERVER_URL,80)
        httpCon.request('GET', constants.PODNAPISI_SEARCH_URL+params)
        xml = httpCon.getresponse().read()
        self.currentSearchKeyword = keyword
        self.initXMLElement(xml)
        self.currentSubsDict = self.getSearchDict()
        self.updateSearchPaginationFromXML()
    
    def initXMLElement(self,xml):
        '''================================================================================================
        ===                      public, initializes the XML to Element object                          ===
        ================================================================================================'''
        self.xmlRootElement = ElementTree.XML(xml)
    
    def updateSearchPaginationFromXML(self):
        '''================================================================================================
        ===                              updateSearchPaginationFromXML                                  ===
        ================================================================================================'''
        pageInfoElement = self.xmlRootElement.find("pagination")
        self.totalSearchPageNumber = int(pageInfoElement.find("count").text)
        self.currentSearchPage = int(pageInfoElement.find("current").text)
        
    def getSearchDict(self):
        '''================================================================================================
        ===             private, returns a dictionary data structure for the currentPage                ===
        ================================================================================================'''
        subtitlesElementList = self.xmlRootElement.findall("subtitle")
        returnedList = {}
        for subElem in subtitlesElementList:
            subID = subElem.find("id").text
            title = subElem.find("title").text
            year = subElem.find("year").text
            movieID = subElem.find("movieId").text
            uploaderID = subElem.find("uploaderId").text
            uploaderName = subElem.find("uploaderName").text
            langID = subElem.find("languageId").text
            langName = subElem.find("languageName").text
            returnedList[subID] = SubInfo(subID, title, year, movieID, uploaderID, uploaderName, langID, langName)
        return returnedList
    def filterSubs(self, sub_title_flag=1, sub_year_flag=1, sub_lang_flag=0, sub_season_flag=0,sub_episode_flag=0):
        return
    
    def nextSearchPage(self):
        '''================================================================================================
        ===              public, returns a dictionary data structure for the nextPage                   ===
        ================================================================================================'''
        self.currentSearchPage += 1
        self.initSubsFromServer(self.currentSearchKeyword, self.currentSearchPage)
        return self.getSearchDict()
    
    def prevSearchPage(self):
        '''================================================================================================
        ===              public, returns a dictionary data structure for the prevPage                   ===
        ================================================================================================'''
        self.currentSearchPage -= 1
        return self.initSubsFromServer(self.currentSearchKeyword, self.currentSearchPage)    
    
    def downloadSub(self,subIdList,location=""):
        downloadReq = self.apiConnection.download(self.sessionID,subIdList)
        self.checkStatus(downloadReq['status'])
        downList = downloadReq['names']
        for downInfo in downList:
            fileName = downInfo['filename']
            zippedStream = urllib.urlopen(constants.PODNAPISI_DOWNLOAD_URL+fileName).read()
            zippedFile = zipfile.ZipFile(StringIO(zippedStream), 'r')
            zippedFile.extractall()
        return "Done"
    
    def checkStatus(self,status):
        try:
            if status != constants.STATUS_OK:
                raise NameError("Invalid Session")
        except NameError:
            print "Invalid Session ..."
        print status